package com.seecen.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seecen.pojo.entity.Account;
import com.seecen.pojo.entity.Tally;
import com.seecen.pojo.vo.AccountWithStatsVO;
import com.seecen.service.AccountService;
import com.seecen.service.TallyService;
import com.seecen.utils.JwtHelper;
import com.seecen.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 账本管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/account")
@CrossOrigin
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private TallyService tallyService;

    @Autowired
    private JwtHelper jwtHelper;

    /**
     * 获取当前用户的账本列表（带统计信息）
     */
    @GetMapping("/list")
    public Result getAccountList(@RequestHeader String token) {
        try {
            Long userId = jwtHelper.getUserId(token);
            
            LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Account::getUserId, userId)
                   .orderByDesc(Account::getCreateTime);
            
            List<Account> accounts = accountService.list(wrapper);
            
            // 为每个账本添加统计信息
            List<AccountWithStatsVO> accountWithStatsList = new ArrayList<>();
            for (Account account : accounts) {
                AccountWithStatsVO vo = new AccountWithStatsVO();
                BeanUtils.copyProperties(account, vo);
                
                // 查询该账本的所有记账记录并统计
                LambdaQueryWrapper<Tally> tallyWrapper = new LambdaQueryWrapper<>();
                tallyWrapper.eq(Tally::getUserId, userId)
                           .eq(Tally::getAccountId, account.getId())
                           .eq(Tally::getIsDeleted, 0);
                
                List<Tally> tallyList = tallyService.list(tallyWrapper);
                
                double totalIncome = 0.0;
                double totalExpense = 0.0;
                
                for (Tally tally : tallyList) {
                    if (tally.getType() == 2) { // 收入
                        totalIncome += tally.getPrice();
                    } else if (tally.getType() == 1) { // 支出
                        totalExpense += tally.getPrice();
                    }
                }
                
                vo.setTotalIncome(totalIncome);
                vo.setTotalExpense(totalExpense);
                vo.setBalance(totalIncome - totalExpense);
                
                accountWithStatsList.add(vo);
            }
            
            log.info("获取账本列表成功，用户ID: {}, 账本数量: {}", userId, accountWithStatsList.size());
            return Result.ok(accountWithStatsList);
        } catch (Exception e) {
            log.error("获取账本列表失败", e);
            return Result.build(null, 500, "获取账本列表失败");
        }
    }

    /**
     * 根据ID获取账本详情
     */
    @GetMapping("/{id}")
    public Result getAccountById(@PathVariable Long id, @RequestHeader String token) {
        try {
            Long userId = jwtHelper.getUserId(token);
            Account account = accountService.getById(id);
            
            if (account == null) {
                return Result.build(null, 404, "账本不存在");
            }
            
            if (!account.getUserId().equals(userId)) {
                return Result.build(null, 403, "无权访问该账本");
            }
            
            log.info("获取账本详情成功，账本ID: {}", id);
            return Result.ok(account);
        } catch (Exception e) {
            log.error("获取账本详情失败", e);
            return Result.build(null, 500, "获取账本详情失败");
        }
    }

    /**
     * 创建新账本
     */
    @PostMapping
    public Result createAccount(@RequestBody Account account, @RequestHeader String token) {
        try {
            Long userId = jwtHelper.getUserId(token);
            
            account.setUserId(userId);
            account.setCreator(userId);
            account.setLastUpdator(userId);
            
            boolean success = accountService.save(account);
            
            if (success) {
                log.info("创建账本成功，用户ID: {}, 账本名称: {}", userId, account.getRemark());
                return Result.ok(account).message("创建账本成功");
            } else {
                return Result.build(null, 500, "创建账本失败");
            }
        } catch (Exception e) {
            log.error("创建账本失败", e);
            return Result.build(null, 500, "创建账本失败");
        }
    }

    /**
     * 更新账本
     */
    @PutMapping("/{id}")
    public Result updateAccount(@PathVariable Long id, @RequestBody Account account, @RequestHeader String token) {
        try {
            Long userId = jwtHelper.getUserId(token);
            
            Account existingAccount = accountService.getById(id);
            if (existingAccount == null) {
                return Result.build(null, 404, "账本不存在");
            }
            
            if (!existingAccount.getUserId().equals(userId)) {
                return Result.build(null, 403, "无权修改该账本");
            }
            
            account.setId(id);
            account.setUserId(userId);
            account.setLastUpdator(userId);
            
            boolean success = accountService.updateById(account);
            
            if (success) {
                log.info("更新账本成功，账本ID: {}", id);
                return Result.ok(account).message("更新账本成功");
            } else {
                return Result.build(null, 500, "更新账本失败");
            }
        } catch (Exception e) {
            log.error("更新账本失败", e);
            return Result.build(null, 500, "更新账本失败");
        }
    }

    /**
     * 删除账本
     */
    @DeleteMapping("/{id}")
    public Result deleteAccount(@PathVariable Long id, @RequestHeader String token) {
        try {
            Long userId = jwtHelper.getUserId(token);
            
            Account account = accountService.getById(id);
            if (account == null) {
                return Result.build(null, 404, "账本不存在");
            }
            
            if (!account.getUserId().equals(userId)) {
                return Result.build(null, 403, "无权删除该账本");
            }
            
            boolean success = accountService.removeById(id);
            
            if (success) {
                log.info("删除账本成功，账本ID: {}", id);
                return Result.ok("删除账本成功");
            } else {
                return Result.build(null, 500, "删除账本失败");
            }
        } catch (Exception e) {
            log.error("删除账本失败", e);
            return Result.build(null, 500, "删除账本失败");
        }
    }
}


